package com.lshl.lingshang.http.file;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * Description：扩展OkHttp的请求体，实现上传时的进度提示
 * Created on 2018/8/16 0016
 * Author : 郭
 */
public class UploadFileRequestBody extends RequestBody {
    private RequestBody mRequestBody;

    //用于进度监听回调
    public interface OnProgressChangeCallBackListener {
        void onProgressChangeCallBack(long bytesWritten, long contentLength);
    }

    OnProgressChangeCallBackListener onProgressChangeCallBackListener;

    //文件类型
    public UploadFileRequestBody(File file) {
        this.mRequestBody = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), file);
//        this.mRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
    }

    //String 类型
    public UploadFileRequestBody(String str) {
        this.mRequestBody = RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), str);
    }

    @Override
    public MediaType contentType() {
        return mRequestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return mRequestBody.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        CountingSink countingSink = new CountingSink(sink);
        BufferedSink bufferedSink = Okio.buffer(countingSink);
        //写入
        mRequestBody.writeTo(bufferedSink);
        //刷新
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }

    protected final class CountingSink extends ForwardingSink {
        private long bytesWritten = 0;

        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            bytesWritten += byteCount;
            if (onProgressChangeCallBackListener != null) {
                onProgressChangeCallBackListener.onProgressChangeCallBack(bytesWritten, contentLength());
            }
        }
    }
}
